<!-- 客户导入窗口 -->
<template>
  <Dialog v-model="dialogVisible" title="产品同步" width="500">
    <div class="flex items-center my-10px">
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="产品类型" prop="formType" class="mb-20px">
          <el-radio-group v-model="queryParams.id">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.CRM_K3_ITEM_TYPE)"
              :onchange="handleItemTypeChange"
              :key="dict.value"
              :value="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择产品" prop="fItemId" class="mb-20px">
          <el-cascader
            clearable
            filterable
            v-model="queryParams.fItemId"
            :options="fItemOptions"
            :props="defaultItemProps"
            class="w-1/1"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="" prop="updateSupport" class="mb-20px">
          <el-checkbox v-model="queryParams.updateSupport" >  是否更新已经存在的产品数据（“产品代码”重复）</el-checkbox>
        </el-form-item>
      </el-form>
<!--      <span class="mr-10px" style="width: 100px">选择产品</span>-->
    </div>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
import * as ProductApi from '@/api/crm/product'
import * as UserApi from '@/api/system/user'
import { defaultProps,defaultItemProps } from '@/utils/tree'
import { useUserStore } from '@/store/modules/user'
import * as AreaApi from "@/api/system/area";
import * as BusinessApi from "@/api/crm/business";

defineOptions({ name: 'ProductImportFormK3' })

const message = useMessage() // 消息弹窗
const queryFormRef = ref() // 搜索的表单
const queryParams = reactive({
  id: undefined,
  fItemId: undefined, // K3产品编号
  updateSupport: undefined,// 是否更新已经存在的客户数据
})

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const ownerUserId = ref<undefined | number>() // 负责人编号
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表

const fItemOptions = ref([]) // 产品分类列表
/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  await resetForm()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  ownerUserId.value = useUserStore().getUser.id

}

const handleItemTypeChange = async () => {
  fItemOptions.value = undefined
  // 查询产品分类
  fItemOptions.value = await ProductApi.initK3ItemSelectionOptions(queryParams);
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const submitForm = async () => {
  /** 提交表单 */
  await message.confirm("您确定拉取K3数据并同步更新吗？");
  formLoading.value = true
  try {
    const data = await ProductApi.handleUpdateByK3(queryParams)
    if(data){debugger
      submitFormSuccess(data)
    }else{
      message.error("拉取K3数据并同步更新失败！")
      formLoading.value = false
      return
    }
    queryFormRef.value.resetFields()
  } catch {
    submitFormError()
  } finally {
    formLoading.value = false
  }
}


/** 文件同步成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {debugger
  // 拼接提示语
  const data = response
  let text = '新增成功数量：' + data.createProductNames.length + ';'
  // for (let name of data.createProductNames) {
  //   text += '< ' + name.split('-')[0] + ' >'
  // }
  text += '更新成功数量：' + data.updateProductNames.length + ';'
  // for (const name of data.updateProductNames) {
  //   text += '< ' + name.split('-')[0] + ' >'
  // }
  text += '失败数量：' + Object.keys(data.failureProductNames).length + ';'
  for (const name in data.failureProductNames) {
    text += '< ' + name + ': ' + data.failureProductNames[name] + ' >'
  }
  message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('同步失败，请您重新同步！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async () => {
  // 重置上传状态和文件
  ownerUserId.value = undefined
  queryFormRef.value.resetFields()
  await nextTick()
}

</script>
